package com.example.service.impl;

import com.example.aop.MyLog;
import com.example.mapper.DeptLogMapper;
import com.example.mapper.DeptMapper;
import com.example.mapper.EmpMapper;
import com.example.pojo.Dept;
import com.example.pojo.DeptLog;
import com.example.pojo.Emp;
import com.example.service.DeptLogService;
import com.example.service.DeptService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private DeptLogService deptLogService;

    @Autowired
    private EmpMapper empMapper;
    @MyLog
    @Override
    public List<Dept> list() {
        return deptMapper.list();
    }

    @Transactional(rollbackFor = Exception.class)//spring事务管理
    @MyLog
    @Override
    public void delete(Integer id) throws Exception {
        try {
            deptMapper.deleteById(id);//删除部门
//        int i=1/0;
            if (true){
                throw new Exception("出错了");
            }
            empMapper.deleteByDeptId(id);//删除员工
        }finally {
            DeptLog deptLog = new DeptLog();
            deptLog.setCreateTime(LocalDateTime.now());
            deptLog.setDescription("删除部门"+id);
            deptLogService.insert(deptLog);
        }
    }

    @Override
    public void add(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());

        deptMapper.insert(dept);
    }
}
